package com.molyfun.parents.zhibo.playback;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.ksyun.media.player.IMediaPlayer;
import com.ksyun.media.player.KSYMediaPlayer;
import com.ksyun.media.player.KSYTextureView;
import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.activity.common.HorizontalShareDialogActivity;
import com.molyfun.parents.fragment.dialog.CommonChooseDialogFragment;
import com.molyfun.parents.impl.NetWorkChangeCallback;
import com.molyfun.parents.rest.RestClient;
import com.molyfun.parents.rest.bean.ZhiboRecordResponse;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.view.zhibo.PlaybackControlView;
import com.molyfun.parents.view.zhibo.ZhiboImListView;
import com.molyfun.parents.zhibo.NetChangeReceiver;
import com.molyfun.parents.zhibo.im.ImModel;
import com.molyfun.parents.zhibo.im.event.EventExecuter;
import com.molyfun.parents.zhibo.im.event.EventHandler;
import com.molyfun.parents.zhibo.impl.IPlaybackIns;
import com.squareup.picasso.Picasso;
import com.tencent.imsdk.TIMConversation;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.molyfun.parents.zhibo.ZhiboActivity.FLAG_ZHIBO_ROOM_SUBJECT_ID;

/**
 * Created by kongweile on 29/10/2016.
 * Auto hide and show navigation bar and status bar for API >= 19.
 * Keep screen on.
 */

public class PlayBackActivity extends BaseActivity implements View.OnClickListener, NetWorkChangeCallback , EventExecuter, IPlaybackIns, PlayBackMsgDispatcher.OnLoadMoreDataListener {

//    public static final String mRoomId = "4028b88162d3cd140162d66f07a40005";

    private static final String TAG = PlayBackActivity.class.getSimpleName();

//    private static final String FLAG_ROOM_ID_TAG = "room_id";
//
//    private static final String FLAG_PLAYBACK_URL = "playback_url";

    public static final String FLAG_VIDEO_RECORD_ID = "video_record_id";
    public static final String FLAG_VIDEO_RECORD_NAME = "video_record_name";
    public static final String FLAG_VIDEO_RECORD_URL = "video_record_url";
    public static final String FLAG_VIDEO_RECORD_TARGET = "video_record_target";
    public static final String FLAG_VIDEO_RECORD_SHOW_SHARE = "video_record_show_share";

    protected TIMConversation conversation;

    private final static int PERMISSION_REQUEST_CAMERA_AUDIOREC = 1;

    @InjectView(R.id.player_view)
    KSYTextureView mPlayerView;

    @InjectView(R.id.zhibo_controller_view)
    PlaybackControlView mPlaybackControlView;
    @InjectView(R.id.game)
    WebView mGameView;
    @InjectView(R.id.zhibo_im_list_view)
    ZhiboImListView mZhiboImListView;
    @InjectView(R.id.user_leave)
    TextView mUserLeave;

    @InjectView(R.id.large_layout_container)
    RelativeLayout mLargeLayoutContainer;
    @InjectView(R.id.top_layout)
    LinearLayout mTopLayout;
    @InjectView(R.id.web_view_container)
    FrameLayout mWebViewContainer;
    @InjectView(R.id.zhibo_container)
    FrameLayout mZhiboContainer;

    @InjectView(R.id.container_layout)
    ImageView mContainerLayout;

    private LinearLayout.LayoutParams webLayoutParams;
    private LinearLayout.LayoutParams zhiboLayoutParams;

//    private String mRoomId = "";
//    private String mPlayBackUrl = "";

    private PlayBackMsgDispatcher mapContainer = new PlayBackMsgDispatcher();
    private int currentLastMsgStamp = 0;

    private String mVideoRecordId, mVideoRecordName, mVideoRecordUrl, mVideoRecordTarget;
    private boolean showShareBtn = true;

//    protected ZhiboListResponse.ZhiboBean zhiboBean;

    protected static final String ZHIBO_BEAN = "zhibo_bean";

    private String mSubjectId;


    public static final void startActivity(Context context, String videoRecordId, String videoRecordName, String videoRecordUrl, String videoRecordTarget, String subjectId) {
        Intent intent = new Intent();
        intent.setClass(context, PlayBackActivity.class);
        intent.putExtra(FLAG_VIDEO_RECORD_ID, videoRecordId);
        intent.putExtra(FLAG_VIDEO_RECORD_NAME, videoRecordName);
        intent.putExtra(FLAG_VIDEO_RECORD_URL, videoRecordUrl);
        intent.putExtra(FLAG_VIDEO_RECORD_TARGET, videoRecordTarget);
        intent.putExtra(FLAG_ZHIBO_ROOM_SUBJECT_ID, subjectId);
        context.startActivity(intent);
    }

    //小组回放，不分享
    public static final void startActivity(Context context, String videoRecordId, String videoRecordName, String videoRecordUrl, boolean showShare) {
        Intent intent = new Intent();
        intent.setClass(context, PlayBackActivity.class);
        intent.putExtra(FLAG_VIDEO_RECORD_ID, videoRecordId);
        intent.putExtra(FLAG_VIDEO_RECORD_NAME, videoRecordName);
        intent.putExtra(FLAG_VIDEO_RECORD_URL, videoRecordUrl);
        intent.putExtra(FLAG_VIDEO_RECORD_SHOW_SHARE, showShare);
        context.startActivity(intent);
    }


    @Override
    public void onMessageNewStr(ImModel.ImStringModel imStringModel) {
        mZhiboImListView.addMsg(imStringModel);
    }

    @Override
    public void onMessageNewUser(ImModel.UserCountModel userCountBody) {

    }

    @Override
    public void onMessageUserOut(ImModel.UserCountModel userCountBody) {

    }

    @Override
    public void onMessageRtcCancel(ImModel.RtcInviteModel rtcInviteModel) {
        if(rtcInviteModel.getData().getTargetuserid().equals(MFPApplication.getInstance().getUser().getId())){
        }
    }

    @Override
    public void onMessageRtcConfim(ImModel.RtcInviteModel rtcInviteModel) {

    }

    @Override
    public void onMessageRtcStop() {

    }

    @Override
    public void onMessageRtcInvite(ImModel.RtcInviteModel rtcInviteModel) {
        mRtcInviteModel = rtcInviteModel;
    }

    @Override
    public void seekTo(int position){
        //如果从最后的位置拖动到之前，需要重新开始请求数据
        hasMoreData = true;

        //定位到一个位置
        //(int)(mPlayerView.getCurrentPosition() / mPlayerView.getDuration()) * 1000
        getData((position * mPlayerView.getDuration())/1000 + "", true);
        mPlayerView.seekTo((position * mPlayerView.getDuration())/1000);

    }

    @Override
    public void onVideoPause(){
        mPlayerView.pause();
    }

    @Override
    public void onVideoPlay(){
        mPlayerView.start();
    }

    @Override
    public void onShare(){
        String shareUrl = "";

        switch (PreferencesStorageUtil.getServerMode(MFPApplication.getInstance())) {
            case PreferencesStorageUtil.ServerMode.OFFICAL:
                shareUrl = "http://h5.helloparents.molyfun.com/#/subject/detail/" + mSubjectId;
                break;
            case PreferencesStorageUtil.ServerMode.PREPARE:
                shareUrl = "http://h5.helloparentstest.molyfun.com/#/subject/detail/" + mSubjectId;
                break;
            case PreferencesStorageUtil.ServerMode.TEST:
                shareUrl = "http://192.168.3.30:8081/helloparents-client/#/subject/detail/  " + mSubjectId;
                break;
        }

        HorizontalShareDialogActivity.sharePage(PlayBackActivity.this, mVideoRecordName, mVideoRecordTarget, shareUrl);
    }

    @Override
    public long getDuration(){
        return mPlayerView.getDuration();
    }

    @Override
    public void onFinish(){
        finish();
    }

    ImModel.RtcStartModel mRtcStartModel;

    @Override
    public void onMessageRtcStart(ImModel.RtcStartModel rtcStartModel){
        mRtcStartModel = rtcStartModel;
//        zhiboControlView.setRtcBegin(true);
//        startConference(rtcStartModel.getData().getChannel());
    }

    @Override
    public void onTeacherEnter() {
        mUserLeave.setVisibility(View.GONE);
        if(mPlayerView != null){
            mPlayerView.prepareAsync();
        }
    }

    @Override
    public void onTeacherLeave() {
        mUserLeave.setVisibility(View.VISIBLE);
        toast("主播已离开房间");
    }

    @Override
    public void onLoadMoreMsg() {
        getData(currentLastMsgStamp + "");
    }

    //获取聊天数据
    public void getData(String timelenstamp){
        getData(timelenstamp, false);
    }

    //获取聊天数据
    public void getData(final String timelenstamp,final boolean isSeek){
        Call<ZhiboRecordResponse> call = MFPApplication.getInstance().getRestClient().getRecordEventList(mVideoRecordId, timelenstamp);
        call.enqueue(new Callback<ZhiboRecordResponse>() {
            @Override
            public void onResponse(Call<ZhiboRecordResponse> call, Response<ZhiboRecordResponse> response) {
                if(response.body() != null){
                    if(response.body().getData() != null && response.body().getData().getRecords().size() > 0){
                        mapContainer.addAll(response.body().getData().getRecords());
                        if(response.body().getData().getRecords() != null && response.body().getData().getRecords().size() > 0){
                            JsonObject jsonObject = response.body().getData().getRecords().get(response.body().getData().getRecords().size() - 1);
                            currentLastMsgStamp = jsonObject.get("timelenstamp").getAsInt();
                            if(response.body().getData().getEvents() != null && response.body().getData().getEvents().size() > 0){
                                for(JsonObject jsonObject1 : response.body().getData().getRecords()){
                                    EventHandler.handlerEvent(jsonObject1.toString(), PlayBackActivity.this);
                                }
                            }
                            if(response.body().getData().getRecords().size() < RestClient.ZHIBO_PLAYBACK_PAGE_SIZE){
                                hasMoreData = false;
                            }
                        }

                        /**
                         * seek之后需要重新刷新数据
                         */
                        if(isSeek){
                            ArrayList<ImModel> msgList = new ArrayList<>();
                            for(JsonObject jsonObject : mapContainer.getDataBySeek(Long.parseLong(timelenstamp))){

                                String eventType = jsonObject.get("eventtype").getAsString();
                                String operType = jsonObject.get("opertype").getAsString();

                                if (!TextUtils.isEmpty(eventType)) {
                                    System.out.println("eventType--->" + eventType);
                                    System.out.println("operType--->" + operType);
                                    switch (eventType) {
                                        case "live":
                                            if (!TextUtils.isEmpty(operType) && operType.equals("groupmsg")) {
                                                msgList.add(GsonUtil.fromJson(jsonObject.toString(), ImModel.ImStringModel.class));
                                            }
                                    }
                                }
                            }
                            System.out.println("msgList--->" + msgList.size());

                            mZhiboImListView.refreshData(msgList);
                        }
                    }else{
                        //可以停止请求聊天了，没有数据了
                        hasMoreData = false;
//                        mTimeHander.removeMessages(FLAG_HANDLER_REFRESH);
                    }
                }
            }

            @Override
            public void onFailure(Call<ZhiboRecordResponse> call, Throwable t) {
                toast("请求失败");
            }
        });
    }

    @Override
    public void onMessageGalleryOperate(final ImModel.GalleryBody galleryBody, int operateType) {
        System.out.println("galleryBody-->"+ GsonUtil.toJson(galleryBody));
        System.out.println("onMessageGalleryOperate-operateType->"+ operateType);
        switch (operateType){
            case ImModel.GalleryOperateType.OperateTypeOpen:

                if(!galleryBody.getGtype().equals("4")){

                    mGameView.loadUrl("javascript:loadMatter('" + galleryBody.getUrl() + "','" + galleryBody.getGtype() + "')");

                    mGameView.setWebViewClient(new WebViewClient() {

                        @Override
                        public void onPageStarted(WebView view, String url, Bitmap favicon) {
                            super.onPageStarted(view, url, favicon);
                        }
                        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                            handler.proceed() ;
                        }

                        @Override
                        public void onPageFinished(WebView view, String url) {
                            super.onPageFinished(view, url);
                            //2视频 3音频 4游戏
                            System.out.println("onPageFinished-->" + galleryBody.getGtype());
                            System.out.println("onPageFinished-js->" + "javascript:playTimeVideo("+ galleryBody.getTimepoint() +")");
                            if(galleryBody.getGtype().equals("2") || galleryBody.getGtype().equals("3")){
                                //                            mGameView.loadUrl("javascript:playTimeVideo(2)");
                                mGameView.loadUrl("javascript:playTimeVideo("+ galleryBody.getTimepoint() +")");
                            }else if(galleryBody.getGtype().equals("3")){
                                mGameView.loadUrl("javascript:playTimeAudio("+ galleryBody.getTimepoint() +")");
                            }
                        }

                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            if (!url.equals("about:blank")) {
                            }
                            return false;
                        }
                    });

//                    mGameView.loadUrl(url);
                }else{
//                    mGameView.loadUrl(galleryBody.getUrl());
                }

                mGameView.loadUrl("javascript:loadMatter('" + galleryBody.getUrl() + "','" + galleryBody.getGtype() + "')");

                break;
            case ImModel.GalleryOperateType.OperateTypeClose:
                mGameView.loadUrl("about:blank");
                break;
            case ImModel.GalleryOperateType.OperateTypePause:
                mGameView.loadUrl("javascript:loadMatter('" + galleryBody.getUrl() + "','" + galleryBody.getGtype() + "')");
                if(galleryBody.getGtype().equals("2")){
                    mGameView.loadUrl("javascript:pauseVideo()");
                }else if(galleryBody.getGtype().equals("3")){
                    mGameView.loadUrl("javascript:pauseAudio()");
                }
                break;
            case ImModel.GalleryOperateType.OperateTypeSeek:
                mGameView.loadUrl("javascript:loadMatter('" + galleryBody.getUrl() + "','" + galleryBody.getGtype() + "')");
                System.out.println("OperateTypeSeek-js->" + "javascript:playTimeVideo("+ galleryBody.getTimepoint() +")");
                if(galleryBody.getGtype().equals("2")){
//                    mGameView.loadUrl("javascript:playTimeVideo(3)");
                    mGameView.loadUrl("javascript:playTimeVideo("+ galleryBody.getTimepoint() +")");
                }else if(galleryBody.getGtype().equals("3")){
                    mGameView.loadUrl("javascript:playTimeAudio("+ galleryBody.getTimepoint() +")");
                }
                break;
        }
    }

    ImModel.RtcInviteModel mRtcInviteModel;

//    protected ZhiboRoomResponse.RoomBean mRoomBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playback);
        ButterKnife.inject(this);

        WebSettings webSettings = mGameView.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);              // 正常加载缓存
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setUseWideViewPort(true);
//        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//        webSettings.setLoadWithOverviewMode(true);
//        mGameView.loadUrl("http://test.molyfun.com/live/preview.html");
//        zhiboBean = getIntent().getParcelableExtra(ZHIBO_BEAN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        mVideoRecordId = getIntent().getStringExtra(FLAG_VIDEO_RECORD_ID);
        mVideoRecordName = getIntent().getStringExtra(FLAG_VIDEO_RECORD_NAME);
        mVideoRecordUrl = getIntent().getStringExtra(FLAG_VIDEO_RECORD_URL);
        mVideoRecordTarget = getIntent().getStringExtra(FLAG_VIDEO_RECORD_TARGET);
        showShareBtn = getIntent().getBooleanExtra(FLAG_VIDEO_RECORD_SHOW_SHARE, true);
        mSubjectId = getIntent().getStringExtra(FLAG_ZHIBO_ROOM_SUBJECT_ID);

//        mRoomId = getIntent().getStringExtra(FLAG_ROOM_ID_TAG);
//        mPlayBackUrl = getIntent().getStringExtra(FLAG_PLAYBACK_URL);

        if(!TextUtils.isEmpty(mVideoRecordUrl)){
            startToPlay(mVideoRecordUrl);
        }

        mZhiboImListView.initData("禁止传播违法违规、封建迷信、暴力血腥、低俗色情、招嫖诈骗、违禁品等不良信息，坚决维护青少年群体精神文明健康。请勿轻信各类招聘征婚、代练代抽、刷钻、购买礼包码、游戏币、电商贩卖等广告信息，以免上当受骗。");

//        mGameView.loadUrl("http://192.168.3.30:8085/openclass/matter.html");
        mGameView.loadUrl(RestClient.COMMON_GALLERY_BASE_URL);

        getData("0");
        NetChangeReceiver.addNetCallback(this);

        webLayoutParams = (LinearLayout.LayoutParams) mWebViewContainer.getLayoutParams();
        zhiboLayoutParams = (LinearLayout.LayoutParams) mZhiboContainer.getLayoutParams();

        mapContainer.setOnLoadMoreDataListener(this);
        mPlaybackControlView.initData(this, mVideoRecordName);
        if(!showShareBtn){
            mPlaybackControlView.setShareVisible(false);
        }

        if(!TextUtils.isEmpty(MFPApplication.getInstance().getUser().getWatermarkurl())){
            Picasso.with(PlayBackActivity.this)
                    .load(MFPApplication.getInstance().getUser().getWatermarkurl())
                    .into(mContainerLayout);

        }

    }

    private static final int PROGRESS_REFRESH_STEP = 200;

    private static final int FLAG_HANDLER_REFRESH = 1001;

    private boolean hasMoreData = true;

    private Handler mTimeHander = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case FLAG_HANDLER_REFRESH:
                    System.out.println("FLAG_HANDLER_REFRESH---->" + mPlayerView.getCurrentPosition() + "mapContainer.size--->" + mapContainer.size());
                    mPlaybackControlView.setProgressBarPosition((int)((mPlayerView.getCurrentPosition() * 1000) / mPlayerView.getDuration()));
                    mTimeHander.sendEmptyMessageDelayed(FLAG_HANDLER_REFRESH, PROGRESS_REFRESH_STEP);

                    mPlaybackControlView.updateTime(mPlayerView.getCurrentPosition());

                    if(mapContainer != null && mapContainer.size() > 0){
                        for(JsonObject jsonObject : mapContainer.getData(mPlayerView.getCurrentPosition(), hasMoreData)){
                            EventHandler.handlerEvent(jsonObject.toString(), PlayBackActivity.this);
                        }
                    }
                    break;
            }
        }
    };

    protected void startToPlay(String url) {
        Log.i("buffer", "视频加载开始了");
        showProgressDialog("加载中...");
        mPlayerView.setOnPreparedListener(mOnPreparedListener);
        mPlayerView.setOnErrorListener(mOnPlayerErrorListener);
        mPlayerView.setOnInfoListener(mOnPlayerInfoListener);
        mPlayerView.setOnCompletionListener(mOnCompletionListener);
        mPlayerView.setVolume(1.0f, 1.0f);
//        startVol = 1.0f;
//        chooseDecode = mSettings.getString("choose_decode", "undefined");
//        bufferTime = mSettings.getInt("buffertime", 2);
//        bufferSize = mSettings.getInt("buffersize", 15);
//        prepareTimeout = mSettings.getInt("preparetimeout", 5);
//        readTimeout = mSettings.getInt("readtimeout", 30);
//        if (bufferTime > 0) {
        mPlayerView.setBufferTimeMax(2);
//        }

//        if (bufferSize > 0) {
        mPlayerView.setBufferSize(15);
//        }
//        if (prepareTimeout > 0 && readTimeout > 0) {
        mPlayerView.setTimeout(5, 30);
//        }
//        if (chooseDecode.equals(Setting.USEHARD)) {
//            useHwDecoder = true;
//        } else {
//            useHwDecoder = false;
//        }
//        if (useHwDecoder) {
//            if (KSYHardwareDecodeWhiteList.getInstance().getCurrentStatus() == KSYHardwareDecodeWhiteList.KSY_STATUS_OK) {
//                if (KSYHardwareDecodeWhiteList.getInstance().supportHardwareDecodeH264()
//                        || KSYHardwareDecodeWhiteList.getInstance().supportHardwareDecodeH265())
        mPlayerView.setDecodeMode(KSYMediaPlayer.KSYDecodeMode.KSY_DECODE_MODE_AUTO);
//            }
//        }

        try {
            mPlayerView.setDataSource(url);
            mPlayerView.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }


    @Override
    protected void onPause() {
        super.onPause();
        /**
         * Step 11: You must stop capture, stop conference, stop streaming when activity paused
         */

    }

    @Override
    protected void onStop() {
        super.onStop();
            mPlayerView.pause();
            mPlaybackControlView.setPauseState(PlaybackControlView.PlaybackState.StatePause);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CAMERA_AUDIOREC: {
                // If request is cancelled, the result arrays are empty.

                break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mGameView != null){
            mGameView.loadUrl("about:blank");
        }
        mTimeHander.removeMessages(FLAG_HANDLER_REFRESH);
        NetChangeReceiver.removeNetCallback(this);
    }

    private IMediaPlayer.OnPreparedListener mOnPreparedListener = new IMediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(IMediaPlayer iMediaPlayer) {
            mPlayerView.setVideoScalingMode(KSYMediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
            mPlayerView.start();
            if(!mTimeHander.hasMessages(FLAG_HANDLER_REFRESH)){
                mTimeHander.sendEmptyMessage(FLAG_HANDLER_REFRESH);
            }

            mPlaybackControlView.updateTotalTime(mPlayerView.getDuration());
            dismissProgressDialog();
        }
    };

    private IMediaPlayer.OnErrorListener mOnPlayerErrorListener = new IMediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
            toast("播放器遇到错误，播放已退出，错误码:" + i, Toast.LENGTH_SHORT);
            videoPlayEnd();
            return false;
        }
    };

    private IMediaPlayer.OnInfoListener mOnPlayerInfoListener = new IMediaPlayer.OnInfoListener() {
        @Override
        public boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1) {
            switch (i) {
                case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
                    showProgressDialog("加载中...");
                    break;
                case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
                    dismissProgressDialog();
                    break;
            }
            return false;
        }
    };


    private IMediaPlayer.OnCompletionListener mOnCompletionListener = new IMediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(IMediaPlayer iMediaPlayer) {
            toast("直播结束");
        }
    };


    private void videoPlayEnd() {
        if (mPlayerView != null) {
            mPlayerView.release();
        }
    }

    @Override
    public void onNetWorkMethodChange(boolean isWifi) {
        new CommonChooseDialogFragment.CommonChooseDialogBuilder("继续观看" , "停止观看", "您正在使用移动网络，继续观看会产生流量费用，建议您在Wi-Fi下观看。")
                .setCommonChooseDialogClickListener(new CommonChooseDialogFragment.CommonChooseDialogClickListener() {
                    @Override
                    public void onConfirm() {
                        //停止拉流
                    }

                    @Override
                    public void onCancel() {
                        //继续观看
                    }
                }).build(getSupportFragmentManager().beginTransaction());
    }

    @Override
    public void onNetWorkAvailableChange(boolean isAvailable) {
        if(!isAvailable){
            toast("断网了");
        }
    }

}
